package com.skyline.jfs.storage.bean.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.skyline.jfs.cluster.model.JFSNodeConfigProper;
import com.skyline.jfs.storage.bean.Storer;
import com.skyline.jfs.storage.dao.JFSStorageDao;
import com.skyline.jfs.storage.model.JFSStreamTranBlock;
import com.skyline.jfs.storage.util.AbsoluteFileNameUtils;

@Component("storer")
public class StorerImpl extends UnicastRemoteObject implements Storer {

	private static final long serialVersionUID = 1L;

	private static Map<String, OutputStream> outputs = new HashMap<String, OutputStream>();

	private static Map<String, Long> fileIDs = new HashMap<String, Long>();

	private JFSStorageDao jfsStorageDao;

	public StorerImpl() throws RemoteException, MalformedURLException {
		super();
	}

	public void startStore(String key) throws IOException, java.rmi.RemoteException {
		//AbsoluteFileNameUtils fileNameUtils=new AbsoluteFileNameUtils();
		Long time = (new Date()).getTime();
		String pathDir = JFSNodeConfigProper.getStorageDirectory() + "/" + AbsoluteFileNameUtils.getPath(time);
		File path = new File(pathDir);
		path.mkdirs();
		String fileDir = JFSNodeConfigProper.getStorageDirectory() + "/"+AbsoluteFileNameUtils.getAbsoluteName(time);
		File file = new File(fileDir);
		try {
			OutputStream out = null;
			out = new BufferedOutputStream(new FileOutputStream(file), JFSStreamTranBlock.BLOCK_SIZE);
			if (outputs.containsKey(key) == false) {
				outputs.put(key, out);
				fileIDs.put(key, time);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void stopStore(String key,Long virtualFileID) throws IOException, java.rmi.RemoteException {
		try {
			OutputStream out = null;
			out = outputs.get(key);
			if (out != null) {
				out.close();
				Long fileID = fileIDs.get(key);
				jfsStorageDao.insertJFSStorage(virtualFileID, JFSNodeConfigProper.getId(),fileID);
			}
		} finally {
			outputs.remove(key);
			fileIDs.remove(key);
		}
	}

	@Override
	public void store(String key, JFSStreamTranBlock block) throws IOException, RemoteException {
		try {
			OutputStream out = null;
			out = outputs.get(key);
			byte[] content = block.getContent();
			if (out != null && content != null) {
				out.write(content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public JFSStorageDao getJfsStorageDao() throws java.rmi.RemoteException {
		return jfsStorageDao;
	}

	public void setJfsStorageDao(JFSStorageDao jfsStorageDao) throws java.rmi.RemoteException {
		this.jfsStorageDao = jfsStorageDao;
	}
}
